package com.binvshe.binvshe.app.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.binvshe.binvshe.app.home.adapter.HomeAdapter;
import com.binvshe.binvshe.common.http.ListDataRequestListener;
import com.binvshe.binvshe.common.http.MyResponseParser;
import com.binvshe.binvshe.entity.HomeEntity;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;

import java.util.List;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2017/2/3
 */

public abstract class BaseOpusFragment extends SwipeListFragment {

    protected final static int PAGE_SIZE = 10;
    protected int lastListSize = 0;
    int mlastid = 0;

    MyResponseParser<HomeEntity> parser = new MyResponseParser<HomeEntity>(HomeEntity.class) {

        @Override
        public boolean hasMore() {
            if (lastListSize >= PAGE_SIZE) {
                return true;
            } else {
                return false;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        startLoading();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    ListDataRequestListener mRequestListener = new ListDataRequestListener(this, parser) {
        @Override
        public void onSuccess(Object listData) {
            super.onSuccess(listData);
            if (getData().size() > 0) {
                mlastid = ((HomeEntity) getData().get(getData().size() - 1)).getId();
            }
            List<HomeEntity> list = (List<HomeEntity>) listData;
            if (list != null) {
                lastListSize = list.size();
            }
        }
    };

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        mlastid = 0;
        getData().clear();
        mRequestListener = new ListDataRequestListener(this, parser) {
            @Override
            public void onSuccess(Object listData) {
                super.onSuccess(listData);
                if (getData().size() > 0) {
                    mlastid = ((HomeEntity) getData().get(getData().size() - 1)).getId();
                }
                List<HomeEntity> list = (List<HomeEntity>) listData;
                if (list != null) {
                    lastListSize = list.size();
                }
            }
        };

        startLoading();
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new HomeAdapter(getContext());
    }

    @Override
    public void onStartLoading() {
        loadData();
    }

    /**
     * 获取数据
     */
    protected abstract void loadData();
}
